package controllerLogin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-member/controller/common"
	"go-member/db"
	"go-member/model"
	"go-member/tool"
	"go-member/validata"
	"strconv"
	"time"
)

// Login
// @Description:登录
// @return gin.HandlerFunc
func Login() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		a := validata.Check(ctx, validata.Login())
		if a != nil {
			common.ErrorBadRequest(ctx, a)
			return
		}
		account := ctx.PostForm("account")
		password := ctx.PostForm("password")
		auth, exists := model.CheckAuth(account, tool.CreateMD5(password))
		if !exists {
			common.Error(ctx, "账号或密码错误")
			return
		}
		idString := strconv.Itoa(int(auth.Id))
		token, _ := tool.EncryptByAes([]byte(idString), tool.CommonKey)
		secondString := tool.GetEnvDefault("redis-life-second", "43200")
		second_, _ := strconv.Atoi(secondString)
		redis := db.InitRedis()
		redis.Set(ctx, fmt.Sprintf("auth:%s", token), idString, time.Duration(second_)*time.Second)
		authStruct := model.ReturnAuth{
			Info:  auth,
			Token: token,
		}
		common.Success(ctx, "操作成功", authStruct)
	}
}
